var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');
var app = getApp();

Page({
  data: {
    categoryList: [],
    productList: [],
    currentCategory: {},
  },
  onLoad: function(options) {
    this.getCategoryList();
    user.getCartCount(); //重新计算购物车总数量
  },
  onShow: function() {
    if (app.globalData.cartCount > 0) {
      wx.setTabBarBadge({
        index: 1,
        text: app.globalData.cartCount + "",
      });
    }
  },
  getCategoryList: function() {
    //CategoryList 加载分类列表
    let that = this;
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.CategoryList).then(function(res) {
      that.setData({
        categoryList: res.data,
        currentCategory: res.data[0]
      });
      that.getProductList(res.data[0].id);
    });
  },
  getProductList: function(id) {
    let that = this;
    util.request(api.ProductList, {
      categoryId: id
    }).then(function(res) {
      that.setData({
        productList: res.dataList
      });
      wx.hideLoading();
    });
  },
  switchCate: function(event) {
    var that = this;
    var currentTarget = event.currentTarget;
    if (this.data.currentCategory.id == event.currentTarget.dataset.id) {
      return false;
    }
    that.setData({
      currentCategory: that.data.categoryList[currentTarget.dataset.index]
    });
    this.getProductList(event.currentTarget.dataset.id);
  }
})